﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using TransformerManager.EF.Database;
using TransformerManager.EF.Models;
using TransformerManager.Shared.Helper;

namespace TransformerManager.Shared.Servers
{
    public class OperationLogService : IOperationLogService
    {
        private readonly AppDBContext _context;
        public OperationLogService(AppDBContext appDBContext)
        {
            _context = appDBContext;
        }

        public async Task<PaginationList<OperationLogs>> GetOperationLogsAsync(
            string userName,
            DateTime operateTimeStart,
            DateTime operateTimeEnd,
            PaginationResourceParameters paginationParams)
        {

            IQueryable<OperationLogs> result = _context.OperationLogs;

            if(!string.IsNullOrEmpty(userName))
            {
                result = result.Where(u => u.UserName == userName);
            }

            result = result.Where(o => o.TimeStamp.Date >= operateTimeStart);

            result = result.Where(o => o.TimeStamp.Date <= operateTimeEnd);

            result = result.OrderByDescending(o => o.TimeStamp);

            return await PaginationList<OperationLogs>.CreateAsync(
                paginationParams.PageNumber,
                paginationParams.PageSize,
                result);
        }

        public async Task<OperationLogs> GetOperationLogByIdAsync(int id)
        {
            return await _context.OperationLogs
                .Where(o => o.Id == id)
                .FirstOrDefaultAsync();
        }

        public async Task<int> GetOperationLogsTotalNumAsync()
        {
            return await _context.OperationLogs
                .CountAsync();
        }

        public void DeleteOperationLogsAsync(int delNum)
        {
            if(delNum <= 0)
            {
                return;
            }

            IQueryable<OperationLogs> delObjects = _context.OperationLogs
                .OrderBy(o => o.TimeStamp).Take(delNum);

            if(delObjects == null || delObjects.Count() == 0)
            {
                throw new ArgumentNullException(nameof(delObjects));
            }
            
            _context.OperationLogs.RemoveRange(delObjects);
        }

        public async Task<bool> SaveChangesAsync()
        {
            return (await _context.SaveChangesAsync() >= 0);
        }
    }
}
